/***
 * 修改搜索
 */
function toChangeSearch(chose){
    $('#text-search').text(chose)
}

/**
 * 搜索
 */
function searchPerm(){
    let searchType = $.trim($('#text-search').text())
    let searchInfo = $.trim($('#input-search-perm').val())
    if(searchInfo === ''){
        location = clearURIExceptPageNow()
    } else
        location = updateCurrentUrlParam(decodeURI(searchType), decodeURI(searchInfo))
}
/**
 * 删除权限
 */
function deletePerm(id){
    $.ajax({
        url: '/admin/perm/permdelete/' + id,
        type: 'POST',
        dataType: 'JSON',
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            open_toast(data['code'] === 1 ? 'success':'fail', data['message'])
        }
    })
}
/**
 * 添加权限
 */
function addPerm(){
    $.ajax({
        url: '/admin/perm/addperm',
        type: 'POST',
        data: decodeURI($("#form-modal-add").serialize()),
        dataType: 'JSON',
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            open_toast(data['code'] === 1 ? 'success' : 'fail', data['message'])
        }
    })
}
/**
 * 修改权限
 */
function modifyPerm(){
    $.ajax({
        url: '/admin/perm/modifyperm',
        type: 'POST',
        data: decodeURI($('#form-modal-modify').serialize()),
        dataType: 'JSON',
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            open_toast(data['code'] === 1 ? 'success':'fail', data['message'])
        }
    })
}
/**
 * 打开修改权限模态框前，渲染模态框
 */
function renderModifyModal(permId){
    if(permId == null){
        // 清空内容
        $('#input-modal-add').val("")
        $('#input-modal-add-permName').val("")
        $('#input-modal-add-url').val("")
        return true
    }
    $('#input-modal-modify').val(permId)

    $.ajax({
        url: '/admin/perm/queryperm/' + permId,
        type: 'POST',
        dataType: 'JSON',
        contentType: "application/json;charset=utf-8",
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            if (data['code'] === 1) {
                // 渲染权限信息到模态框
                $('#input-modal-modify-permName').val(data['response']['permName'])
                $('#input-modal-modify-url').val(data['response']['url'])
            } else open_toast('fail', data['message'])
        }
    })
}
/**
 * 渲染权限页面
 */
function renderPerms(perms){
    $x = $('#tobdy-perm')
    // 清空信息
    $x.html("")
    $.each(perms, (index, perm) => {
        $x.append(`
            <tr>
                <td>${perm['id']}</td>
                <td>${perm['permName']}</td>
                <td><a href="${perm['url']}">${perm['url']}</a></td>
                <td>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#div-modal-modify" onclick="renderModifyModal(${perm['id']})">编辑</button>
                    <button class="btn btn-danger" onclick="deletePerm(${perm['id']})">删除</button>
                </td>
            </tr>
        `)
    })

}

/**
 * 渲染切换页面的信息
 */
function renderPage(pageInfo){
    $('#div-admin-perm-page').html('')

    // 首先设置每一页的HTML
    let $perPageInfo = $('<li></li>')
    for (let i in `${pageInfo.navigatepageNums}`) {
        if(i === '0' || i > pageInfo.pages) continue
        $perPageInfo.append(`
    <li>
        <a
            href="${updateCurrentUrlParam('pageNum', i)}" 
            class="page-link d-block text-dark ${i == pageInfo.pageNum ? ' bg-primary' : ''}">
            ${i}
        </a>
    </li>
    `)
    }
    // 如果页数大于1在进行渲染
    if(pageInfo.pages > 1){
        $('#div-admin-perm-page').html(`
     <!-- 分页部分 -->
    <h1 class="u-text-sm text-center">第${pageInfo.pageNum}页 共${pageInfo.pages}页</h1>
    <nav aria-label="Page navigation" class="u-text-sm">
        <ul class="pagination justify-content-center">
            <!--首页-->
            <li class="page-item">
                <a class="page-link d-block text-dark" href="${updateCurrentUrlParam('pageNum', pageInfo.navigateFirstPage)}">
                    首页
                </a>
            </li>
            <!--上一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNum', pageInfo.prePage)}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>`
                + $perPageInfo.html() +
                `
            <!--下一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNum', pageInfo.nextPage)}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
            <!--最后一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNum', pageInfo.navigateLastPage)}">
                    末页
                </a>
            </li>
        </ul>
    </nav>`)
        }
    $('#textShowResult').html(`共${pageInfo.total}条结果`)
}
/**
 * 获取所有的权限数据
 */
function loadPermsData(){
    $.ajax({
        url: '/admin/perm/queryAllPerms',
        type: 'POST',
        data: getUrlParamToJSON(),
        dataType: 'JSON',
        contentType: "application/json;charset=utf-8",
        error: (err) => {
            console.error(err.responseText)
        },
        success: (data) => {
            if (data['code'] === 1) {
                console.log(data)
                // 渲染数据
                renderPerms(data['response']['list'])
                renderPage(data['response'])
            }
        }
    })
}

/**
 * 成功弹窗关闭后 -> 关闭模态框，并刷新窗口
 */
$('#toast-success').bind('hidden.bs.toast', function () {
    $('.btn-modal-cancel').click()
    location.reload()
})
loadPermsData()